﻿ 
var FlashAgentX = {};
FlashAgentX.loaded = false ;
FlashAgentX.socket = null;
FlashAgentX.isConnected = false;
FlashAgentX.retryLimit = 10;
FlashAgentX.retry = 1;
FlashAgentX.errorCount = 1;
FlashAgentX.whenErrorNeedReconnect = true;
FlashAgentX.reconTimeout = null;
FlashAgentX.isCallIngNum = "";
FlashAgentX.agentRole="0";

//定义交易吗
FlashAgentX.SVCCODE_CHECKIN = 1001;
FlashAgentX.SVCCODE_CHECKIN2 = 1002;
FlashAgentX.SVCCODE_CALLSEAT = 1003;
FlashAgentX.SVCCODE_CALLTOUSER = 1004;
FlashAgentX.SVCCODE_CALLUSER = 1005;
FlashAgentX.SVCCODE_CHECKOUT = 1006;
FlashAgentX.SVCCODE_DROPTOUSER = 1007;
FlashAgentX.SVCCODE_DROPUSER = 1008;
FlashAgentX.SVCCODE_FREESEAT = 1009;
FlashAgentX.SVCCODE_GOTOFLOW = 1010;
FlashAgentX.SVCCODE_HOLDERUSER = 1011;
FlashAgentX.SVCCODE_INMEET = 1012;
FlashAgentX.SVCCODE_INSERT = 1013;
FlashAgentX.SVCCODE_MONITER = 1014;
FlashAgentX.SVCCODE_OFFLINE = 1015;
FlashAgentX.SVCCODE_ONLINE = 1016;
FlashAgentX.SVCCODE_OUTINSERT = 1017;
FlashAgentX.SVCCODE_OUTMEET = 1018;
FlashAgentX.SVCCODE_OUTMONITER = 1019;
FlashAgentX.SVCCODE_PLAYDTMF = 1020;
FlashAgentX.SVCCODE_REGISTAGCINFO = 1021;
FlashAgentX.SVCCODE_ROBCALL = 1022;
FlashAgentX.SVCCODE_SETBUSY = 1023;
FlashAgentX.SVCCODE_STOPCALL = 1024; //9.5.6   强拆其他坐席
FlashAgentX.SVCCODE_TOCHECKIN = 1025;
FlashAgentX.SVCCODE_TOCHECKOUT = 1026;
FlashAgentX.SVCCODE_TRANSSEAT = 1027;
FlashAgentX.SVCCODE_UNHOLDERUSER = 1028;
FlashAgentX.SVCCODE_RECOVER = 1029;
FlashAgentX.SVCCODE_WHISPER = 1030; // 耳语
FlashAgentX.SVCCODE_OUTWHISPER = 1031; //结束耳语
FlashAgentX.SVCCODE_TOSETBUSY = 1032; //代示忙或闲  
FlashAgentX.SVCCODE_AUTHVERIFY = 1100; //鉴权成功 
FlashAgentX.SVCCODE_HEARTBEAT = 1101; // 获取坐席状态
FlashAgentX.SVCCODE_GETAGENTSTATUS = 1102; // 获取坐席状态
FlashAgentX.SVCCODE_EVENT_AGENTSTATUS = 1103; // 获取坐席状态
FlashAgentX.SVCCODE_EVENT_CALLINFO = 1104; // 获取坐席通话信息
FlashAgentX.SVCCODE_EVENT_RING = 1105; // 电话振铃
FlashAgentX.SVCCODE_EVENT_ANSWER = 1106; // 电话接听
FlashAgentX.SVCCODE_EVENT_HUNGUP = 1107; // 电话挂机
FlashAgentX.SVCCODE_EVENT_RING3 = 1108; // 获取坐席通话信息
FlashAgentX.SVCCODE_EVENT_ANSWER3 = 1109; // 获取坐席通话信息
FlashAgentX.SVCCODE_EVENT_HUNGUP3 = 1110; // 获取坐席通话信息
FlashAgentX.SVCCODE_EVENT_BECHECKOUT = 1111;
FlashAgentX.SVCCODE_GETAGENTMESSAGE = 1112; // 获取坐席状态
FlashAgentX.SVCCODE_GETCALLEVENT_STATUS = 1113;
FlashAgentX.SVCCODE_GETSTATEEVENT_STATUS = 1115;
FlashAgentX.SVCCODE_GETAGENTLIST = 2001;
FlashAgentX.SVCCODE_GETENTQUEINFO = 2002;

FlashAgentX.g_WSUrl = "";

FlashAgentX.g_HostOffMillis = 0;

FlashAgentX.g_masterUri = "";
FlashAgentX.g_slaveUri = "";
FlashAgentX.g_uri = "";
FlashAgentX.g_OptId = "";
FlashAgentX.g_extNum = "";
FlashAgentX.g_entId = "";
FlashAgentX.g_entpwd="";
FlashAgentX.g_agentPwd = "";
FlashAgentX.g_willdoSendbuff = "";
FlashAgentX.g_callEvent = null;
FlashAgentX.g_callState = null;
FlashAgentX.g_TokenId = "";
FlashAgentX.outsecond=60;
FlashAgentX.presrvicecode=0;


FlashAgentX.heartCheck = { 
    timeout: 8000, //60秒
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function() {
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
    },
    start: function() {
        var self = this;
        this.timeoutObj = setTimeout(function() {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常,readyState==1 链接为open状态 
            if (FlashAgentX.socket && FlashAgentX.socket.readyState == 1){ 
                FlashAgentX.socket.send("ping");
                console.log("ping");   
            }
            self.serverTimeoutObj = setTimeout(function() { //如果超过一定时间还没重置，说明后端主动断开了
                if (FlashAgentX.socket && FlashAgentX.socket.readyState == 3)
                    FlashAgentX.socket.close(); //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout)
        }, this.timeout);
    }
};
FlashAgentX.connect = function() {
    showSubStatus & showSubStatus("connect " + FlashAgentX.g_WSUrl);
    if ('WebSocket' in window) {
        FlashAgentX.socket = new WebSocket(FlashAgentX.g_WSUrl);
    } else if ('MozWebSocket' in window) {
        FlashAgentX.socket = new MozWebSocket(FlashAgentX.g_WSUrl);
    } else {
        console.log('Error: 当前浏览器不支持websocket');
        return;
    }
    window.addEventListener("unload", function(evt) {
        console.log('unload...');
        //FlashAgentX.socket.close();
    });
    FlashAgentX.socket.onopen = function() {
        FlashAgentX.isConnected = true;
        clearTimeout(FlashAgentX.reconTimeout);
        FlashAgentX.retry = 1;
        //心跳检测重置
        FlashAgentX.heartCheck.reset().start();
        if (FlashAgentX.g_willdoSendbuff != "") {
            FlashAgentX.socket.send(FlashAgentX.g_willdoSendbuff);
            FlashAgentX.g_willdoSendbuff = "";
        }
        console.log('connection opened');
    };
    FlashAgentX.socket.onclose = function(ev) {
        showSubStatus && showSubStatus('onclose :' + ev.code + " reason:" + ev.reason);
        //CloseNoActiveClient 
        console.log('connection closed:reason:' + ev.reason + ",code:" + ev.code);
        if (ev.code == 1004 && ev.reason != 'CloseNoActiveClient' ) {
            //如果是重复登录 不需要尝试重连
            FlashAgentX.whenErrorNeedReconnect = false; 
            onCallState && onCallState(0);
            onLogout && onLogout();
            if (ev.reason != "checkout") alert (ev.reason);
            return ;
        }
        FlashAgentX.errorCount++;
        FlashAgentX.isConnected = false;
        FlashAgentX.reconnect();
      
    };
    FlashAgentX.socket.onmessage = function(msg) {
        //如果获取到消息，心跳检测重置
        //拿到任何消息都说明当前连接是正常的
        FlashAgentX.heartCheck.reset().start();
        var data = msg.data;
        if (data.indexOf("pong")>=0) { //心跳
        	//console.log("pong"); 
        	var pvar = data.split("#&");
        	if(pvar.length>1){
        		if(FlashAgentX.presrvicecode>0 && FlashAgentX.presrvicecode!=parseInt(pvar[1])){
        			FlashAgentX.presrvicecode=parseInt(pvar[1]);
        			switch (FlashAgentX.presrvicecode) {
            		case FlashAgentX.SVCCODE_EVENT_AGENTSTATUS:
                	{
            				try{
                    	//do nothing
                    }catch(err){
                    	//
                    }
                    return;
                	}
            		case FlashAgentX.SVCCODE_GETSTATEEVENT_STATUS:
                	{
            				try{
                    	//do nothing
                    }catch(err){
                    	//
                    }
                    return;
                	}
            		case FlashAgentX.SVCCODE_EVENT_RING:
                	{
            				try{
                    	onCallState(12);
                    }catch(err){
                    	//
                    }
                    return;
                	}
            		case FlashAgentX.SVCCODE_EVENT_RING3:
            			{
            				try{
                    	onCallState && onCallState(15);
                    }catch(err){
                    	//
                    }
                    return;
                	}
            		case FlashAgentX.SVCCODE_EVENT_ANSWER:
                	{
            				try{
                    	onCallState(3);
                    }catch(err){
                    	//
                    }
                    return;
                	}
            		case FlashAgentX.SVCCODE_EVENT_ANSWER3:
                	{
            				try{
                    	//do nothing;
                    }catch(err){
                    	//
                    }
                    return;
                	}
            		case FlashAgentX.SVCCODE_EVENT_HUNGUP:
            			{
            				try{
                    	onCallState(1);
                    }catch(err){
                    	//
                    }
                    return;
                	}
            		case FlashAgentX.SVCCODE_EVENT_HUNGUP3:
            			{
            				try{
                    	//do nothing
                    }catch(err){
                    	//
                    }
                    return;
                	}
            		case FlashAgentX.SVCCODE_CHECKIN:
            		case FlashAgentX.SVCCODE_CHECKIN2:
            			{
            				try{
                    	onLogin && onLogin(FlashAgentX.g_OptId);
                    }catch(err){
                    	//
                    }
                    return;
                	}
                //签出，忽略结果
            		case FlashAgentX.SVCCODE_CHECKOUT:
            		case FlashAgentX.SVCCODE_EVENT_BECHECKOUT:
            			{
            				try{
                    	onCallState && onCallState(0);
                    }catch(err){
                    	//
                    }
                    try{
                    	onLogout && onLogout();
                    }catch(err){
                    	
                    }
                    return;
                	}
            		case FlashAgentX.SVCCODE_CALLUSER:
            			{
            				try{
                    	//do nothing
                    }catch(err){
                    	//
                    }
                    return;
                	}
            		case 1007:
                	{
                    FlashAgentX.unholduser();
                    break;
                	} //当退出咨询后，向acd发起恢复客户电话请求
            		case 1009:
                	{
                    FlashAgentX.unholduser();
                    break;
                	}
            		case 1023:
                	{
                    break;
                	}
            		case FlashAgentX.SVCCODE_HOLDERUSER:
            			{
            				try {
            					setButtonStyle("btn_hold_unhold",1,0);
            				}catch(err){
                    	//
                    }
            				break;
            			}
            		case FlashAgentX.SVCCODE_UNHOLDERUSER:
	            		{
            				try {
	        						setButtonStyle("btn_hold_unhold",0,0);
            				}catch(err){
                    	//
                    }
	        					break;
	        				}
            		case FlashAgentX.SVCCODE_INMEET:
	            		{
            				onCallState && onCallState(8);
	        					break;
	        				}
            		case FlashAgentX.SVCCODE_MONITER:
            			{
        						onCallState && onCallState(8);
        						break;
        					}
            		case FlashAgentX.SVCCODE_GETAGENTLIST:
            			{
        						break;
        					}
            		case FlashAgentX.SVCCODE_GETENTQUEINFO:
            			{
            				break;
        					}
            		default:
                	{
            		
                	}
        			}
        		}
        	} 
          return;
        }
        
        console.log(data);
        showSubStatus && showSubStatus("recive:" + data);
        var _data = JSON.parse(msg.data);
        FlashAgentX.presrvicecode=parseInt(_data.head.servicecode);
        switch (parseInt(_data.head.servicecode)) {
            case FlashAgentX.SVCCODE_EVENT_AGENTSTATUS:
                {
            		OnPlatCallState(_data.body.callstate);
            		if(_data.body.agentrole!=null && _data.body.agentrole!="" && _data.body.agentrole!="undefined"){
            			FlashAgentX.agentRole = _data.body.agentrole;
            		}
            		try{
                    	onCallState0 && onCallState0(_data.body);
	                    showSubStatus & showSubStatus("FlashAgentX.SVCCODE_EVENT_AGENTSTATUS " + _data.body.statetime + "  client:" + new Date().getTime() + " server:" + _data.body.hostmillis);
	                    showSubStatus & showSubStatus("FlashAgentX.SVCCODE_EVENT_AGENTSTATUS  与主机时差ms： " + (new Date().getTime() - _data.body.hostmillis));
                    }catch(err){
                    	//
                    }
                    return;
                }
            case FlashAgentX.SVCCODE_GETSTATEEVENT_STATUS:
                {
                    //恢复状态 事件
            		try{
	                    showSubStatus & showSubStatus("FlashAgentX.SVCCODE_GETSTATEEVENT_STATUS client:" + new Date().getTime() + " server:" + _data.body.state.hostmillis);
	                    FlashAgentX.g_callEvent = _data.body.evt;
	                    FlashAgentX.g_callEvent.offts = new Date().getTime() - Number(FlashAgentX.g_callEvent.hostmillis);
	                    onCallState0 & onCallState0(_data.body.state);
	                    if (FlashAgentX.g_callEvent.callstate == 1) OnRingTime && OnRingTime(FlashAgentX.g_callEvent);
            		}catch(err){
                    	//
                    }
            		
            		OnPlatCallState(_data.body.state);
                    return;
                }
            case FlashAgentX.SVCCODE_AUTHVERIFY:
                {
            		//只触发消息，不改变状态计时
            		try{
            			FlashAgentX.g_callEvent = _data.body;
            		}catch(err){
                    	//
                }

            		try{
            			var calltype1=FlashAgentX.g_callEvent.direct;
            			var caller1=FlashAgentX.g_callEvent.caller;
            			var called1=FlashAgentX.g_callEvent.called;
            			var callid1=FlashAgentX.g_callEvent.usid;
            			var queueid1=FlashAgentX.g_callEvent.queueid;
            			var recfile1=FlashAgentX.g_callEvent.recfile;
            			var dataccid1=decodeURIComponent(decodeURIComponent(FlashAgentX.g_callEvent.dataccid));
            			if(calltype1!=null && calltype1=="1"){
            				OnAuthSuccess(calltype1,caller1,callid1,queueid1,dataccid1);
            			}else{          			
            				OnAuthSuccess(calltype1,called1,callid1,queueid1,dataccid1);
            			}
            		}catch(err1){
            			
            		}
                    return;
                }
            case FlashAgentX.SVCCODE_EVENT_RING:
                {
                    // onCallState && onCallState(12);
            		
            		try{
            			FlashAgentX.g_callEvent = _data.body;
            			FlashAgentX.g_callEvent.offts = new Date().getTime() - Number(FlashAgentX.g_callEvent.hostmillis);
	                OnRingTime && OnRingTime(_data.body);
            		}catch(err){
                    	//
                }
            		
            		onCallState(12);
            		
            		try{
            			var calltype1=FlashAgentX.g_callEvent.direct;
            			var caller1=FlashAgentX.g_callEvent.caller;
            			var called1=FlashAgentX.g_callEvent.called;
            			var callid1=FlashAgentX.g_callEvent.usid;
            			var queueid1=FlashAgentX.g_callEvent.queueid;
            			var recfile1=FlashAgentX.g_callEvent.recfile;
            			var dataccid1=decodeURIComponent(decodeURIComponent(FlashAgentX.g_callEvent.dataccid));
            			if(calltype1!=null && calltype1=="1"){
            				OnCalling(calltype1,caller1,callid1,queueid1,dataccid1);
            			}else{          			
            				OnCalling(calltype1,called1,callid1,queueid1,dataccid1);
            			}
            		}catch(err1){
            			
            		}
                    return;
                }
            case FlashAgentX.SVCCODE_EVENT_RING3:
                {
                    //onCallState && onCallState(15);
            		try{
	                    showSubStatus && showSubStatus("FlashAgentX.SVCCODE_EVENT_RING3  " + _data.body.called3);
	                    FlashAgentX.g_callEvent = _data.body;
	                    FlashAgentX.g_callEvent.offts = new Date().getTime() - Number(FlashAgentX.g_callEvent.hostmillis);
            		}catch(err){
                    	//
                    }
            		onCallState && onCallState(15);
                    return;
                }
            case FlashAgentX.SVCCODE_EVENT_ANSWER:
                {
                    //onCallState && onCallState(3);
            		try{
	                    FlashAgentX.g_callEvent = _data.body;
	                    FlashAgentX.g_callEvent.offts = new Date().getTime() - Number(FlashAgentX.g_callEvent.hostmillis);
	                    OnAnswer && OnAnswer(_data.body);
            		}catch(err){
                    	//
                    }
            		onCallState(3);
            		try{
            			var calltype1=FlashAgentX.g_callEvent.direct;
            			var caller1=FlashAgentX.g_callEvent.caller;
            			var called1=FlashAgentX.g_callEvent.called;
            			var callid1=FlashAgentX.g_callEvent.usid;
            			var queueid1=FlashAgentX.g_callEvent.queueid;
            			var recfile1=FlashAgentX.g_callEvent.recfile;
            			var dataccid1=decodeURIComponent(decodeURIComponent(FlashAgentX.g_callEvent.dataccid));
            			if(calltype1!=null && calltype1=="1"){
            				OnCallConnect(calltype1,caller1,callid1,queueid1,recfile1,dataccid1);
            			}else{          			
            				OnCallConnect(calltype1,called1,callid1,queueid1,recfile1,dataccid1);
            			}
            		}catch(err1){
            			
            		}
                    return;
                }
            case FlashAgentX.SVCCODE_EVENT_ANSWER3:
                {
            		try{
	                    FlashAgentX.g_callEvent = _data.body;
	                    FlashAgentX.g_callEvent.offts = new Date().getTime() - Number(FlashAgentX.g_callEvent.hostmillis);
	                    OnAnswer3 && OnAnswer3(_data.body);
	                    showSubStatus && showSubStatus("FlashAgentX.SVCCODE_EVENT_ANSWER3  " + _data.body.called3);
            		}catch(err){
                    	//
                    }
                    return;
                    //return OnAnswer3 && OnAnswer3(_data.body.args);
                }
            case FlashAgentX.SVCCODE_EVENT_HUNGUP:
                {
            		try{
	                    showSubStatus && showSubStatus("FlashAgentX.SVCCODE_EVENT_HUNGUP  " + _data.body);
	                    OnHungupTime && OnHungupTime(_data.body);
            		}catch(err){
                    	//
                    }
            		onCallState(1);
            		try{
            			var calltype1=FlashAgentX.g_callEvent.direct;
            			OnCallHangup(calltype1);
            		}catch(err1){
            			
            		}
            		FlashAgentX.g_callEvent = null;
                    return;
                }
            case FlashAgentX.SVCCODE_EVENT_HUNGUP3:
                {
            		try{
	                    FlashAgentX.g_callEvent = _data.body;
	                    FlashAgentX.g_callEvent.offts = new Date().getTime() - Number(FlashAgentX.g_callEvent.hostmillis);
	                    showSubStatus && showSubStatus("FlashAgentX.SVCCODE_EVENT_HUNGUP3  " + _data.body.called3);
            		}catch(err){
                    	//
                    }
                    //          var offts = new Date().getTime() - Number(FlashAgentX.g_callState.hostmillis);
                    //        var tdt    = new Date(FlashAgentX.g_callState.statetime.toString().replace(/-/g,"/")) ;
                    //      var rDt =  new Date(  tdt  + offts );
                    //    onCallState0 && onCallState0(FlashAgentX.g_callState.callstate,rDt);
                }


                //onLogin
            case FlashAgentX.SVCCODE_CHECKIN:
            case FlashAgentX.SVCCODE_CHECKIN2:
                {
                    if (_data.head.errcode == 0) {
                        //计算服务器与客户机时差
                        var clientTime = new Date().getTime();
                        FlashAgentX.g_HostOffMillis = clientTime - Number(_data.body.hostmillis);
                        g_logined = 1;
                        if ("110" == _data.body.tokenid) {
                            //  g_AcdInfo.isCheckIn = true;
                            // var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_GETCALLEVENT_STATUS, {});
                            //doSend(buf);
                            return;
                        }
                        //alert("tokenid:::"+_data.body.tokenid);
                        FlashAgentX.g_TokenId = _data.body.tokenid;
                        g_TokenId = _data.body.tokenid;
                        return onLogin && onLogin(FlashAgentX.g_OptId);
                    } else {
                        if (_data.head.errcode == -19200) {
                            if (confirm("您的工号已在其他地方签入，要继续签入吗？")) {
                                FlashAgentX.checkin2();
                            }
                        } else
                        	{                         	 
	                        	try{
	                        		showMessage && showMessage ("登录失败:" + _data.head.errmsg);
	                        	}catch(err){
	                            	//
	                            }
                        	}
                        return;
                    }
                }
                //签出，忽略结果
            case FlashAgentX.SVCCODE_CHECKOUT:
                {
                    //if(_data.head.errcode == 0)
                    //  g_logined = 2;
                    // disconnect();
            		onCallState && onCallState(0);
            		try{
	                    onLogout && onLogout();
            		}catch(err){
                    	//
                    }
                    return;
                }
            case FlashAgentX.SVCCODE_EVENT_BECHECKOUT:
                {
                    //    g_logined = 2;
                    //  disconnect();
                    onCallState && onCallState(0);
                    try{
                    	onLogout && onLogout();
                    }catch(err){
                    	
                    }
                    // alert(_data.body.args);
                    return;
                }
            case FlashAgentX.SVCCODE_CALLUSER:
                {
                    console.log("呼出失败，errcode =" + _data.head.errcode + " errmsg=" + _data.head.errmsg)
                    // alert(_data.body.args);
                     if (_data.head.errcode == "-19200") {
                        alert("对不起，系统正在呼出 ，请稍后再试！");
                        try{
                        	showMessage && showMessage("对不起，系统正在呼出 ，请稍后再试！");
                        }catch(err){
                    		
                    	}
                        return;
                    }
                    if (_data.head.errcode != "0") {
                    	alert("对不起,呼出失败[" + _data.head.errmsg + "]");
                    	try{
                    		showMessage && showMessage("对不起,呼出失败[" + _data.head.errmsg + "]");
                    	}catch(err){
                    		
                    	}
                    } 
                    return;
                }

            case 1007:
                {
                    FlashAgentX.unholduser();
                    break;
                } //当退出咨询后，向acd发起恢复客户电话请求
            case 1009:
                {
                    FlashAgentX.unholduser();
                    break;
                }
            case 1023:
                {

                    break;
                }
            case FlashAgentX.SVCCODE_HOLDERUSER:
            	{
            		try {
            			setButtonStyle("btn_hold_unhold",1,0);
            		}catch(err){
                    	//
                    }
            		break;
            	}
            case FlashAgentX.SVCCODE_UNHOLDERUSER:
	            {
            		try {
	        			setButtonStyle("btn_hold_unhold",0,0);
            		}catch(err){
                    	//
                    }
	        		break;
	        	}
            case FlashAgentX.SVCCODE_INMEET:
	            {
            		onCallState && onCallState(8);
	        		break;
	        	}
            case FlashAgentX.SVCCODE_MONITER:
            {
        		onCallState && onCallState(8);
        		break;
        	}
            case FlashAgentX.SVCCODE_GETAGENTLIST:
            {
        		//onCallState && onCallState(8);
            	agentlists=_data.body;
            	agentgetflag="1";
        		break;
        	}
            case FlashAgentX.SVCCODE_GETENTQUEINFO:
            {
        		//onCallState && onCallState(8);
            	entques=_data.body;
            	entgetflag="1";
        		break;
        	}
            default:
                {
            		
                }
        }
        try{
	        console.log(msg);
	    }catch(err){
        	//
        }
    };
    FlashAgentX.socket.onerror = function(e) {
        onCallState(-1);
        try{
        	console.log(e);
        	showSubStatus && showSubStatus("socect error " + e);
        }catch(err){
        	//
        }

    };
};
FlashAgentX.init = function() {
    try {
        if (!FlashAgentX.isConnected)
            FlashAgentX.connect();
    } catch(e) {
    	 try {
	        showSubStatus && showSubStatus('连接出错:' + e + ",url:" + FlashAgentX.g_WSUrl);
	        console.log('连接出错:' + e + ",url:" + FlashAgentX.g_WSUrl);
	    }catch(err){
	    	//
	    }
    }
};

FlashAgentX.reconnect = function() {
    var retryLimit = FlashAgentX.retryLimit;
    var retry = FlashAgentX.retry;
    //&& retry <= retryLimit && FlashAgentX.errorCount <= retryLimit
    if (FlashAgentX.whenErrorNeedReconnect && !FlashAgentX.isConnected) {
        console.log('开始连接第' + (FlashAgentX.retry++) + "次");

        // if (FlashAgentX.retry % 4 == 3)
        //     switchAcdGate();
        //   if (retry == 1) { FlashAgentX.init(); } else {
        // FlashAgentX.init();
        FlashAgentX.reconTimeout = window.setTimeout(FlashAgentX.init, 10000);
        //  }
    }
};
console.log('开始初始化连接');
//FlashAgentX.init(); 


 FlashAgentX.doSend = function(buffer) {
    if (buffer == "") return;
    if (!FlashAgentX.whenErrorNeedReconnect) {
        FlashAgentX.whenErrorNeedReconnect = true;
        FlashAgentX.g_willdoSendbuff = buffer;
        FlashAgentX.connect();
        return;
    }
    if (FlashAgentX.socket && FlashAgentX.socket.readyState == 1) {
        try {
            FlashAgentX.socket.send(buffer);
        } catch(e) {
            console.log('doSend error:' + e);
        }
    } else {
        FlashAgentX.g_willdoSendbuff = buffer;
        FlashAgentX.socket.close();
        FlashAgentX.connect();
    }
};

function switchAcdGate() {
    if (FlashAgentX.g_slaveUri == "") return;
    FlashAgentX.g_TokenId = uuid();
    if (FlashAgentX.g_uri == FlashAgentX.g_masterUri)
        FlashAgentX.g_uri = FlashAgentX.g_slaveUri;
    else
        FlashAgentX.g_uri = FlashAgentX.g_masterUri;
    FlashAgentX.g_WSUrl = FlashAgentX.g_uri + FlashAgentX.g_TokenId + "/" + FlashAgentX.g_OptId;
    console.log("系统切换新的acdgate:" + FlashAgentX.g_WSUrl);
}

/********************************************
 * 交易报文打包 
 * @param trCode ：交易码
 * @author trBody ：交易正文
 * @returns {String} 
 ********************************************/
FlashAgentX.packHost=function (trCode, trBody) {
    if (FlashAgentX.g_OptId == "") {
        console.log("pack error " + trCode + " flashagentx not init !");
        return "";
    }

    var headStr = "\"head\":{\"hostcode\":\"" + trCode + "\",\"entid\":" + FlashAgentX.g_entId + ",\"optid\":\"" + FlashAgentX.g_OptId + "\",\"tokenid\":\"" + FlashAgentX.g_TokenId + "\"}";
    var bodyStr = "\"body\":" + JSON.stringify(trBody);
    var doSendBuffer = "{" + headStr + "," + bodyStr + "}";
    console.log("doSend:" + doSendBuffer);
    return doSendBuffer;
}

//JSON转换为字符串
function JSONstringify(Json) {
    if ($.browser.msie) {
        if ($.browser.version == "7.0" || $.browser.version == "6.0") {
            var result = jQuery.parseJSON(Json);
        } else {
            var result = JSON.stringify(Json);
        }
    } else {
        var result = JSON.stringify(Json);
    }
    return result;
}


//提供crm的外部接口
FlashAgentX.loadConfig = function(entId,entPwd, masterUri, slaveUri, agentId, agentPwd, extNum) {
    try {
        FlashAgentX.g_TokenId = FlashAgentX.uuid();
        //alert("这里测试acdgate,生产环境须注释掉 maserturi=...");
        // masterUri = "ws://127.0.0.1:8080/AcdGate/softPhone/" ;
        //masterUri = "ws://cloudcall.58.com:1931/AcdGate/softPhone/" ;
        //slaveUri = "ws://cloudcall.58.com:1930/AcdGate/softPhone/" ;
        //    masterUri = "ws://cloudcall.58.com:1936/AcdGate/softPhone/" ;
        //  alert("注意：投产时 masterUri 须注释");
        // masterUri = "ws://10.245.2.106:8081/AcdGateBeta/softPhone/";
        console && console.log ("您当前绑定分机:" + g_AcdInfo.extNum );
        FlashAgentX.g_masterUri = masterUri;
        FlashAgentX.g_slaveUri = slaveUri;
        FlashAgentX.g_uri = masterUri;
        FlashAgentX.g_OptId = agentId;
        //if(extNum!=null && extNum!=""){        	
        	FlashAgentX.g_extNum = extNum;
        //}else{
        //	FlashAgentX.g_extNum = agentId;
        //}
        FlashAgentX.g_entId = entId;
        FlashAgentX.g_entpwd = entPwd;
        FlashAgentX.g_agentPwd = agentPwd;
        FlashAgentX.g_WSUrl = FlashAgentX.g_uri + FlashAgentX.g_TokenId + "/" + FlashAgentX.g_OptId;
        if (!FlashAgentX.isConnected) {
            FlashAgentX.connect();
            setTimeout(function() {
                FlashAgentX.checkin();
            }, 1000);
        }
        console.log(FlashAgentX.g_WSUrl);
        FlashAgentX.loaded = true ; //参数加载成功
    } catch(e) {
        console.log('连接出错:' + e + ",url:" + FlashAgentX.g_WSUrl);
    }

}
FlashAgentX.checkin = function() {
    var trBody = { //交易请求正文  
        "hotline": "",
        "pass": FlashAgentX.g_agentPwd,
        "station": FlashAgentX.g_extNum,
        "entpwd": FlashAgentX.g_entpwd,
        "stationtype": 0,
        "checkintype": 0,
        "outsecond":FlashAgentX.outsecond
    };
    var buf = FlashAgentX.packHost(FlashAgentX.SVCCODE_CHECKIN, trBody);
    FlashAgentX.doSend(buf);
}
FlashAgentX.checkin2 = function() {
    var trBody = { //交易请求正文  
        "hotline": "",
        "pass": FlashAgentX.g_agentPwd,
        "station": FlashAgentX.g_extNum,
        "entpwd": FlashAgentX.g_entpwd,
        "stationtype": 0,
        "checkintype": 0,
        "outsecond":FlashAgentX.outsecond
    };
    var buf = FlashAgentX.packHost(FlashAgentX.SVCCODE_CHECKIN2, trBody);
    FlashAgentX. doSend(buf);

}
FlashAgentX.online = function() {
    var buf = FlashAgentX.packHost(FlashAgentX.SVCCODE_ONLINE, {});
    FlashAgentX.doSend(buf);
}
FlashAgentX.offline = function() {
    var buf = FlashAgentX.packHost(FlashAgentX.SVCCODE_OFFLINE, {});
    FlashAgentX.doSend(buf);
}
FlashAgentX.checkout = function() {
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_CHECKOUT, {});
    FlashAgentX.doSend(buf);
}
//查询座席列表(只查询在线座席)
FlashAgentX.obtainaenglist = function(agentids) {
    var trBody = { //交易请求正文  
        "agentids": agentids
    };
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_GETAGENTLIST, trBody);
    FlashAgentX.doSend(buf);
}
//查询队列状态
FlashAgentX.obtainqueinfo = function(queid) {
    var trBody = { //交易请求正文  
        "queid": queid
    };
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_GETENTQUEINFO, trBody);
    FlashAgentX.doSend(buf);
}
FlashAgentX.calluser = function(telno, exinfo) {
    var trBody = { //交易请求正文  
        "telno": telno,
        "exinfo": exinfo
    };
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_CALLUSER, trBody);
    FlashAgentX.doSend(buf);
}
FlashAgentX.dropcall = function() //挂机
    {
        var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_DROPUSER, {});
        FlashAgentX.doSend(buf);
    }
FlashAgentX.makecall = function(telno, exinfo) //
    {
        var telno2 = telno.replace(/(^\s*)|(\s*$)/g, "");
        if (FlashAgentX.isCallIngNum == telno2) {
            console.log("Calling " + telno2 + "，稍后再试!");
            return;
        }

        FlashAgentX.isCallIngNum = telno2;

        var trBody = { //交易请求正文  
            "telno": telno2,
            "exinfo": exinfo
        };
        var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_CALLUSER, trBody);
        FlashAgentX.doSend(buf);
        setTimeout(function() {
            FlashAgentX.isCallIngNum = "";
        }, 3000);
    }
FlashAgentX.consult = function(telno, exinfo) //calluser 实现呼出，咨询等，因此这里统一一个函数
    {
        var trBody = { //交易请求正文  
            "telno": telno,
            "exinfo": exinfo
        };
        var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_CALLTOUSER, trBody);
        FlashAgentX.doSend(buf);
    }

FlashAgentX.freeseat = function() //结束内线咨询
    {
        var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_FREESEAT, {});
        FlashAgentX.doSend(buf);
    }

FlashAgentX.droptouser = function() //结束外线咨询
    {
        var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_DROPTOUSER, {});
        FlashAgentX.doSend(buf);
    }
    //0 示闲，1 示忙，2 小休
FlashAgentX.setSeatState = function(type) //calluser 实现呼出，咨询等，因此这里统一一个函数
    {
        var trBody = { //交易请求正文  
            "type": type
        };
        var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_SETBUSY, trBody);
        FlashAgentX.doSend(buf);
    }
FlashAgentX.holduser = function() { FlashAgentX.doSend(FlashAgentX.packHost(FlashAgentX.SVCCODE_HOLDERUSER, {})); }
FlashAgentX.unholduser = function() { FlashAgentX.doSend(FlashAgentX.packHost(FlashAgentX.SVCCODE_UNHOLDERUSER, {})); }
    //转坐席
FlashAgentX.transseat = function() { FlashAgentX.doSend(FlashAgentX.packHost(FlashAgentX.SVCCODE_TRANSSEAT, {})); }
    //转坐席
FlashAgentX.transcall = function() { FlashAgentX.doSend(FlashAgentX.packHost(FlashAgentX.SVCCODE_TRANSSEAT, {})); }

FlashAgentX.gotoivr = function(flowtype,rootactid, actid, extinfo) {
    //var info = "flow:" + rootactid + ";" + actid + ";" + extinfo;
    var info = flowtype+":" + rootactid + ";" + actid + ";" + extinfo;
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_GOTOFLOW, { "flowno": info });
    FlashAgentX.doSend(buf);
}
FlashAgentX.inmeet = function() //会议
    {
        var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_INMEET, {});
        FlashAgentX.doSend(buf);
    }
FlashAgentX.outmeet = function() //会议
    {
        var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_OUTMEET, {});
        FlashAgentX.doSend(buf);
    }
FlashAgentX.callseat = function(toseatno) //咨询座席
{
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_CALLSEAT, { "toseatno": toseatno });
    FlashAgentX.doSend(buf);
}
// (toWorkNo, callDataHelper.getCallData());
FlashAgentX.callseatEx = function(toseatno, extinfo) //calluser 实现呼出，咨询等，因此这里统一一个函数
    {
        var info = toseatno + ";" + extinfo;
        var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_CALLSEAT, { "toseatno": info });
        FlashAgentX.doSend(buf);
    }
FlashAgentX.transqueue = function(queueid, extinfo) //calluser 实现呼出，咨询等，因此这里统一一个函数
    {
        var info = "q:" + queueid + ";" + extinfo;
        var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_CALLSEAT, { "toseatno": info });
        FlashAgentX.doSend(buf);
    }
    //发起监听， toseatno 被监听坐席工号
FlashAgentX.monitor = function(toseatno) {
    var trBody = { //交易请求正文  
        "toseatno": toseatno,
    };
    monedagentno = toseatno;
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_MONITER, trBody);
    FlashAgentX.doSend(buf);
}
FlashAgentX.outmoniter = function(toseatno) {
    var trBody = { //交易请求正文  
        "toseatno": toseatno,
    };
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_OUTMONITER, trBody);
    FlashAgentX.doSend(buf);
}

//插话=会议
FlashAgentX.insert = function() {
        var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_INSERT, {});
        FlashAgentX.doSend(buf);
    }
//退出会议
FlashAgentX.outinsert = function() {
        var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_OUTINSERT, {});
        FlashAgentX.doSend(buf);
    }
    //耳语=指导坐席
FlashAgentX.whisper = function() {
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_WHISPER, {});
    FlashAgentX.doSend(buf);
}
FlashAgentX.outwhisper = function() {
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_OUTWHISPER, {});
    FlashAgentX.doSend(buf);
}
FlashAgentX.robcall = function() {
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_ROBCALL, {});
    FlashAgentX.doSend(buf);
};
FlashAgentX.stopcall = function() {
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_STOPCALL, {});
    FlashAgentX.doSend(buf);
};
FlashAgentX.tocheckout = function(toseatno) {
    var trBody = { //交易请求正文  
        "toseatno": toseatno,
    };
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_TOCHECKOUT, trBody);
    FlashAgentX.doSend(buf);
};
FlashAgentX.tosetbusy = function(toseatno, type) {
    var trBody = { //代示忙或闲       
        "toseatno": toseatno,
        "type": type
    };
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_TOSETBUSY, trBody);
    FlashAgentX.doSend(buf);
};

FlashAgentX.getAgcListState= function(worknos) {
    var trBody = {
        "worknos": worknos // 工号
    }
    agentgetflag = "2";
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_GETAGENTLIST, trBody);
    FlashAgentX.doSend(buf);
};

FlashAgentX.getEntQueueList= function(queid) {
    var trBody = {
    		"queueid": queid
    }
    entgetflag="2";
    var buf =FlashAgentX.packHost(FlashAgentX.SVCCODE_GETENTQUEINFO, trBody);
    FlashAgentX.doSend(buf);
};

FlashAgentX.uuid =function () { 
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
};
 